package com.itheima.health.Security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SecurityUserDetails implements UserDetailsService {

    // 模拟数据库的用户记录，如下User类是health_common中的自定义实体类User
    // 修改Role、Permission，为其增加不带参、带参构造方法
    private static Map<String, User> userDb = new HashMap();
    static {
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword("{noop}1234");
        // 用户权限与角色
        Role role1 = new Role("系统管理员","ROLE_ADMIN");
        role1.getPermissions().add(new Permission("添加权限","add"));
        role1.getPermissions().add(new Permission("删除权限","delete"));
        role1.getPermissions().add(new Permission("更新权限","update"));
        role1.getPermissions().add(new Permission("查询权限","find"));
        user1.getRoles().add(role1);
        userDb.put(user1.getUsername(),user1);

        User userZhangSan = new User();
        userZhangSan.setUsername("zhangsan");
        userZhangSan.setPassword("{noop}1234");
        Role role2 = new Role("数据分析员","ROLE_READER");
        role2.getPermissions().add(new Permission("查询权限","find"));

        Role roleTest = new Role("运营管理员","ROLE_OMS");;
//        roleTest.getPermissions().add(new Permission("添加权限","add"));
//        roleTest.getPermissions().add(new Permission("更新权限","update"));

        userZhangSan.getRoles().add(role2);
        userZhangSan.getRoles().add(roleTest);
        userDb.put(userZhangSan.getUsername(),userZhangSan);

        User userLisi = new User();
        userLisi.setUsername("lisi");
        userLisi.setPassword("{noop}1234");
        Role role3 = new Role("运营管理员","ROLE_OMS");;
        role3.getPermissions().add(new Permission("添加权限","add"));
        role3.getPermissions().add(new Permission("更新权限","update"));
        userLisi.getRoles().add(role3);
        userDb.put(userLisi.getUsername(),userLisi);
    }

    /*
        1. 根据用户标识（用户名），从数据库读取用户信息
        2. 提取用户信息的角色与权限关键词信息
        3. 把用户角色与权限关键词封装为List<GrantedAuthority>列表
        4. 构建UserDetail对象（使用Security框架自动的User类封装），封装用户名、密码（必须是加密过的）及权限角色关键词列表
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //从数据库中查找（为了省事直接从内存中读取，应该直接从数据中读取）
        User user =  userDb.get(name);
        //判断传入的用户在数据库中是否存在
        if (user==null){
            throw new  UsernameNotFoundException("您输入的用户未找到");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        //获取用户的所有角色
        for (Role role : user.getRoles()) {
            //向容器中添加角色
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            System.out.println("存入role中的Keyword: "+role.getKeyword());
            //获取用户的所有权限
            for (Permission permission : role.getPermissions()) {
                //向容器中添加每个角色对应的权限
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                System.out.println("存入permission中的Keyword: "+permission.getKeyword());
            }
        }

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+authorities);//[ROLE_OMS, ROLE_READER, find]
        //返回封装后的security中的user（username，password，authorities）
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }




}
